package com.my.study.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

/**
 * @author: yidujun
 * @create: 2021/05/12 15:25
 */
@Slf4j
public class SpringUtils implements ApplicationContextAware, EnvironmentAware {
    private static ApplicationContext applicationContext;
    private static Environment environment;

    public static ApplicationContext getApplicationContext() {
        if (null == applicationContext) {
            log.warn("please defined SpringUtils bean");
            return null;
        }
        return applicationContext;
    }

    public static Environment getEnvironment() {
        if (null == environment) {
            log.warn("please defined SpringUtils bean");
            return null;
        }
        return environment;
    }


    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    @Override
    public void setEnvironment(Environment environment) {
        SpringUtils.environment = environment;
    }
}
